package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class PictureServiceImpl implements PictureService {

    @Value("${pic.local-path}")
    private String localPath;

    @Override
    public String savePicture(MultipartFile multipartFile) {
        // 创建目录
        File dir = new File(localPath);
        if (!dir.exists()) {
            //dir.mkdir()，不使用mkdir，假如创建目录为 /c 要放到 /a/b 目录下，使用mkdir不会创建/a/b，而mkdirs则会
            dir.mkdirs();
        }

        /**
         * 创建索引
         *
         * aaa.jpg -> xxx.jpg
         * 获取当前文件的全名称、后缀名
         */

        String fileName = multipartFile.getOriginalFilename();
        assert fileName != null;
        //拿到后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //拼接
        fileName = UUID.randomUUID() + suffix;

        //图片保存,将图片写进目标目录下
        try {
            multipartFile.transferTo(new File(localPath + "/" + fileName));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PICTURE_UPLOAD_ERROR);
        }

        return fileName;
    }
}
